########################################
# Author: Healer
# Email: healer_kx@163.com
# 
# 
# 

require File.join(File.expand_path(File.dirname(__FILE__)), 'base.rb')


class Compiler

	#
	def append_begin
		content=<<HCJ_BEGIN
$fragments = 
{
'null'					:'<strong>Null</strong>',
'undefined'				:'<strong>Undefined</strong>',
HCJ_BEGIN
		@file.write content
	end

	#
	def append_end
		@file.write "};"
	end

	#
	def append(key, value)
		line = "'#{key}'\t\t\t:\"#{value}\",\n"
		@file.write line
	end

	#
	def compile_file filename
		file = File.new filename, 'r'
		content = file.read

		filename =~ /Views\/(.*)/i
		key = if ($1)
			$1
		else
			filename =~ /Widgets\/(thtml\/.*)/i
			$1
		end
		

		# Deal with Quote.
		content = content.gsub(/"/).each{|c| c[0] = "\\\"" }
		content = content.gsub(/[\r]/, '')
		content = content.gsub(/[\n]/).each{|c| c[0] = "\\n" }

		append key.downcase, content
	end

	#
	def compile_files paths
		paths.each do |path|
			Dir.foreach(path) do |file| 
				filename = File.join(path, file);
				if File.directory? filename
					compile_files [filename] if not file.start_with? '.'
      			elsif file.end_with? '.html'
        			
        			compile_file filename
      			end
    		end
		end
	end

	#
	def compile paths, dest
		if (File.exists? dest)
			puts "File '#{dest}' Exists..."
			#return
		end
		@file = File.new dest, 'w'
		append_begin
		compile_files paths
		append_end
		
	end

	def close
		@file.close if @file
	end
end


def compile paths, dest

	compiler = Compiler.new
	compiler.compile(paths, dest)
	compiler.close

end







# Main
# ruby compile.rb new html.compiled.js
if $mode_name === Everest::ModeNew
	paths = []
	view_path 		= File.join( File.expand_path(File.dirname(__FILE__)), '..', 'Tpl/Home/Views' )
	widget_tpl_path = File.join( File.expand_path(File.dirname(__FILE__)), '..', 'Tpl/Home/Widgets/thtml' )
	paths << view_path
	paths << widget_tpl_path
	dest = $module_name
	dest = 'html.compiled.js' if !$module_name
	dest = File.join( File.expand_path(File.dirname(__FILE__)), '..', 'Tpl/Home/Views', dest )
	compile paths, dest
end

